/**
 * create by zhangpu
 * date:2015年3月12日
 */
package com.acooly.module.openapi.client.provider.jyt.marshall;

import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiUnmarshal;
import com.acooly.module.openapi.client.api.message.MessageFactory;
import com.acooly.module.openapi.client.provider.jyt.JytConstants;
import com.acooly.module.openapi.client.provider.jyt.domain.JytNotify;
import com.acooly.module.openapi.client.provider.jyt.enums.JytServiceEnum;
import com.acooly.module.openapi.client.provider.jyt.utils.XmlUtils;
import com.acooly.module.safety.Safes;
import com.acooly.module.safety.key.KeyLoadManager;
import com.acooly.module.safety.signature.SignTypeEnum;
import com.acooly.module.safety.support.KeyStoreInfo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author zhangpu
 */
@Service
@Slf4j
public class JytNotifyUnmarshall extends JytMarshallSupport
        implements ApiUnmarshal<JytNotify, Map<String, String>> {
    private static final Logger logger = LoggerFactory.getLogger(JytNotifyUnmarshall.class);
    @Resource(name = "jytMessageFactory")
    private MessageFactory messageFactory;

    @Autowired
    private KeyLoadManager keyStoreLoadManager;

    @SuppressWarnings("unchecked")
    @Override
    public JytNotify unmarshal(Map<String, String> message, String serviceName) {
        try {
            logger.info("异步通知{}", message);
            String signature = message.get(JytConstants.SIGN);
            String xmlEnc = message.get(JytConstants.XML_ENC);
            String keyEnc = message.get(JytConstants.KEY_ENC);
            String partnerId = message.get(JytConstants.MERCHANT_NO);
            //解密响应报文
            String respXml = decryptKey(keyEnc,xmlEnc);
            KeyStoreInfo keyStoreInfo = keyStoreLoadManager.load(partnerId, JytConstants.PROVIDER_NAME);
            Safes.getSigner(SignTypeEnum.Cert).verify(respXml,keyStoreInfo,signature);
            log.info("验签成功");
            return doUnmarshall(respXml, serviceName);
        } catch (Exception e) {
            throw new ApiClientException("异步通知 解析失败:" + e.getMessage());
        }

    }

    protected JytNotify doUnmarshall(String notifyXml, String serviceName) {
        JytNotify notify = (JytNotify) messageFactory.getNotify(serviceName);
        notify = XmlUtils.toBean(notifyXml,notify.getClass());
        notify.setService(JytServiceEnum.find(serviceName).getCode());
        return notify;
    }

    public void setMessageFactory(MessageFactory messageFactory) {
        this.messageFactory = messageFactory;
    }

}
